package com.example.HaiDLaobackend.config;

import com.example.HaiDLaobackend.common.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String auth = request.getHeader("Authorization");
        if (auth != null && auth.startsWith("Bearer ")) {
            String token = auth.substring(7);
            try {
                Claims claims = JwtUtil.parse(token);
                Object uid = claims.get("uid");
                if (uid != null) {
                    request.setAttribute("currentUserId", Long.valueOf(uid.toString()));
                }
            } catch (Exception ignored) {}
        }
        return true;
    }
}


